<?php if(!defined('BASEPATH')) exit('No direct script access allowed!');

class Test_Question_Student_Model extends MY_Model {
	protected $_table_name = 'test_question_student';

	public function __construct() {
		parent::__construct();
	}	
	
	public function insert(&$input) {
		
		$this->db->where('question_detail_id', $_SESSION['question_detail_id']);
		$this->db->where('nis',$_SESSION['user']);
		$this->db->where('test_id',$_SESSION['test_id']);
		$rs = $this->db->get('test_question_student')->result_array();
		
		echo var_dump($rs) . "testing";
		if(count($rs)<=0) //jangan simpan jawaban siswa yang kembar (untuk handle tombol submit ditekan berulang2 karena loading / lack jaringan komputer)
		{
			$data = array();
			$data['test_id'] = $_SESSION['test_id'];
			
			if(!isset($_SESSION['problem_no']))
				$_SESSION['problem_no']=1;
			else
				$_SESSION['problem_no'] = $_SESSION['problem_no'] + 1;
				
			$data['question_detail_id'] = $_SESSION['question_detail_id'];
			$data['number_in_test'] = $_SESSION['no'];
			$data['nis'] = $_SESSION['user'];
			$data['student_answer'] = $input->post($_SESSION['question_detail_id']);
			/*
			echo "Kunci jawaban = " . $this->get_question_detail_answer($_SESSION['question_detail_id']) . "<br>";
			echo "Siswa menjawab = ". $data['student_answer'] . "<Br>";
			echo "hasil perbandingan = " . ($this->get_question_detail_answer($_SESSION['question_detail_id']) == $data['student_answer']) ."<Br>";
			*/
			if( $this->get_question_detail_answer($_SESSION['question_detail_id']) == $data['student_answer'] )
				$data['judge'] = 1;
			else
				$data['judge'] = 0;
			
			$this->db->insert($this->_table_name,$data);
		}
	}
	
	public function get_question_detail_answer($question_detail_id){
		$this->db->where('id', $question_detail_id);
		$rs = $this->db->get('questions_detail')->result_array();
		return $rs[0]['answer'];
	}
	
	public function is_exist($question_detail_id, $nis, $test_id){
		$this->db->where('question_detail_id', $question_detail_id);
		$this->db->where('nis', $nis);
		$this->db->where('test_id', $test_id);
		$rs = $this->db->get('test_question_student')->result_array();
		return count($rs);
	}
	
	public function is_done($test_id, $nis){
		$this->db->where('test_id', $test_id);
		$this->db->where('nis', $nis);
		$rs = $this->db->get('test_question_student')->result_array();
		//echo $this->db->last_query() . " " . count($rs) . " " . $_SESSION['total_qty'];
		
		if (count($rs) == $_SESSION['total_qty'])
			return true;
		else
			return false;
		
	}
	
	public function get_last_number($test_id, $nis){
		$this->db->where('test_id', $test_id);
		$this->db->where('test_question_student.nis', $nis);
		$rs = $this->db->get('test_question_student')->result_array();
		return count($rs)+1;
	}
	
	public function delete($id){
		$this->db->delete($this->_table_name, array('test_id'=>$id));
	}

}
